
import { storeToRefs } from 'pinia';
import { useAuthSotre } from '../sotre/authStore';
import router from './index'
import { useMenuStore } from '../sotre/useMenuSotre';
import KeepAlive from '../views/keepAlive/KeepAlive.vue';
const modules = import.meta.glob("../views/**/**.vue");

//不需要被拦截的页面
const whites=['/login','/wechatLogin','/asyncComponent','/keepalive','/keepedit','/scheduledemo','/directive','/map']
//需要被缓存的页面
const keepAlivePages=['/market/elderly']


//是否添加过动态路由
let isAddRouter = false;
router.beforeEach(async (to, from) => {

  console.log("isAddRouter",isAddRouter);

  console.log("to.path",to.path);
  
  
  console.log("whites.includes(to.path)",whites.includes(to.path));
  

  
    if (whites.includes(to.path)) {
      return true
    }
    const authStore = useAuthSotre();
    const { token } = storeToRefs(authStore);
   

    if (!token.value) {
      return '/login'
    }
  
    // let routerLength = router.getRoutes().length;

    // if(routerLength>3) return true;
  
    if(isAddRouter)  return true;
    isAddRouter=true;
    
    const menuStore = useMenuStore();
    await menuStore.getMenus();

    console.log("  menuStore.routerMenus",  menuStore.routerMenus);


    
  
    menuStore.routerMenus.forEach(item => {
  
      item.children?.forEach(child => {

        let component = modules[`../views/${item.url}/${child.pathName}.vue`];

        console.log(`/${item.url}/${child.url}`);
        
        console.log(`../views/${item.url}/${child.pathName}.vue`);
        
   
        if (!component) {
          component = modules[`../../views/404.vue`];
        }
  
        router.addRoute('Layout', {
          path: `/${item.url}/${child.url}`,
          name: child.url + child.id,
          component: component,
          meta: {
            keepAlive:keepAlivePages.includes(`/${item.url}/${child.url}`)
          }
        })
  
  
      })
  
  
    })
  
    return to.fullPath;

  
  })